import { _decorator, Component, instantiate, Label, Node, Prefab, UI } from 'cc';
import { UserInfo } from '../common/UserInfo';
import { MapZone } from '../entity/MapZone';
import { OasisItem } from './OasisItem';
import { buildingType } from '../settings/const';
import { UIManager } from '../common/UIManager';
import VillageApi from '../api/VillageApi';
import { EventManager } from '../event/EventManager';
const { ccclass, property } = _decorator;

@ccclass('Oasis')
export class Oasis extends Component {
    @property(Label)
    desc:Label
    @property(Node)
    content:Node
    @property(Prefab)
    oasisItem:Prefab
    @property(Node)
    cancelTitle:Node
    @property(Node)
    cancelContent:Node


    start() {
        this.init()

        EventManager.instance.on(EventManager.EventType.RefreshOasisList, this.init, this)
    
        this.cancelTitle.active = false
    }

    init(){
        this.getOasisList()
        this.getCancelOasisList()
    }

    async getOasisList(){
        let zoneList = []
        await UserInfo.instance.refreshVillageDetail()
        let oasisList = UserInfo.instance.villageData.oasisList
        console.log(oasisList)
        for(let item of oasisList){
            var zone = MapZone.createByObj(item)
            
            zoneList.push(zone)
        }

        this.content.destroyAllChildren()
        for(let zone of zoneList){
            let node = instantiate(this.oasisItem)
            this.content.addChild(node)
            node.getComponent(OasisItem).setData(zone)
        }


        let building = UserInfo.instance.getBManageById(buildingType.B37_HeroMasion)
        if(building){
            let max = 0
            if(building.grade >= 10){
                max = 1
            }
            if(building.grade >= 15){
                max = 2
            }
            if(building.grade >= 20){
                max = 3
            }
            this.desc.string = `等级${building.grade}，最多可占领${max}块绿洲，当前已占领${zoneList.length}块。`
        } else {
            this.desc.string = ''
        }
        
    }

    async getCancelOasisList(){
        await UIManager.instance.showLoading()
        let res = await VillageApi.canceledOasisList()
        UIManager.instance.closeLoading()
        let list:MapZone[] = []
        for(let item of res.data){
            list.push(MapZone.createByObj(item))
        }
        this.cancelContent.destroyAllChildren()
        for(let item of list){
            let node = instantiate(this.oasisItem)
            this.cancelContent.addChild(node)
            node.getComponent(OasisItem).setData(item)
        }

        if(list.length == 0){
            this.cancelTitle.active = false
            this.cancelContent.active = false
        } else {
            this.cancelTitle.active = true
            this.cancelContent.active = true
        }
        
    }

}


